package com.ziyun.pop.web.config;

import java.io.PrintWriter;
import java.util.Arrays;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.web.filter.AccessControlFilter;

import com.alibaba.fastjson.JSONObject;

import io.renren.common.utils.R;
import org.springframework.beans.factory.annotation.Value;

/**
 * 接口拦截器
 *
 * @author zh
 * @date 2018/9/414:30
 */
public class PortFilter extends AccessControlFilter {

	private  String[] whiteList ;

	private boolean openWhite;


	PortFilter (boolean openWhite, String whiteList){
		this.openWhite = openWhite;
		this.whiteList = whiteList.split(",");
	}

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		return false;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		// String ip = IPUtils.getIPAddress((HttpServletRequest) request);

		String serverName = request.getServerName();
		System.out.println("serverName" + serverName);
		if (!openWhite){ // 关闭白名单 则直接通过
			return  true;
		}else if ( Arrays.asList(whiteList).contains(serverName)) { // 判断白名单
			return true;
		} else {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html; charset=utf-8");
			PrintWriter out = response.getWriter();
			out.println(JSONObject.toJSON(R.error("当前ip无权限访问该接口!")));
			out.flush();
			out.close();
			return false;
		}
	}
}
